package com.pbd.client.utils;

import java.util.HashMap;
import java.util.Map;

public class QueryParameters {
	//private Map map = new HashMap();
	private Map<String,Object> map = new java.util.TreeMap<String,Object>
    (String.CASE_INSENSITIVE_ORDER);

	private String[] nameValues;

	public QueryParameters() {

	}

	public void populateQueryString() {
		String search = getQueryString();
		if ((search != null) && (search.length() > 0)) {
			String[] nameValues = search.substring(1).split("&");
			for (int i = 0; i < nameValues.length; i++) {
				String[] pair = nameValues[i].split("=");
				map.put(pair[0], pair[1]);
			}
		}
	}

	public void populateURL() {
		String search = getHostName();
		if ((search != null) && (search.length() > 0)) {
			if ((search != null) && (search.length() > 0)) {
				String tempSearch = search;
				tempSearch = tempSearch.replace(".", "@");
				nameValues = tempSearch.split("@");
			}
		}
	}

	public String getUrlSubDomainAt(int level) {
		if (level < 0)
			throw new RuntimeException("Negative values are not allowed.");
		if (nameValues != null && nameValues.length > level)
			return nameValues[level];
		return null;
	}

	public int getTotalNoOfSubDomain() {
		if (nameValues != null)
			return nameValues.length;
		return -1;
	}

	public String getValue(String key) {
		return (String) map.get(key);
	}

	public boolean containsKey(String key) {
		return map.containsKey(key);
	}

	private native String getQueryString()
	/*-{ 
	      return $wnd.location.search; 
	}-*/;

	private native String getHostName()
	/*-{ 
	      return $wnd.location.hostname; 
	}-*/;
	public static native void redirect(String url)/*-{
    $wnd.location = url;
}-*/;

}
